import { defineStore } from 'pinia';

export const useHomeStore = defineStore('home', {
	state: () => {
		return {
			backgroundAudioManager: uni.getBackgroundAudioManager(),
			isLoading: false,
			data: [],
			title: "",
			subTitle: "",
			player: {
				music: null,
				paused: true, // 当前是是否暂停或停止状态，true 表示暂停或停止，false 表示正在播放
				duration: 0, // 当前音频的长度（单位：s）
				currentTime: 0, // 当前音频的播放位置（单位：s），只有在当前有合法的 src 时返回
			}
		};
	},
	actions: {
		load: function(cb) {
			this.isLoading = true;
			uni.request({
				url: "https://prenatal-music.oss-cn-hangzhou.aliyuncs.com/home.json",
				method: 'GET',
				complete: (res) => {
					this.isLoading = false;
				},
				success: (res) => {
					if (res.statusCode === 200) {
						let data = res.data;
						this.title = data.title;
						this.subTitle = data.subTitle;
						this.data = data.music;

						cb();
					} else {
						cb(new Error("网络不给力！"))
					}
				},
				fail(err) {
					cb(new Error("网络不给力！"))
				}
			})
		},
		setMusic: function(music) {
			if (!this.backgroundAudioManager.paused) {
				this.backgroundAudioManager.pause();
			}
			this.player.music = music;

			this.backgroundAudioManager.title = music.name;
			this.backgroundAudioManager.singer = music.singer;
			this.backgroundAudioManager.src = music.src;

			// 背景音频停止事件
			this.backgroundAudioManager.onStop(() => {
				this.player.music = null;
			})

			// 背景音频播放事件
			this.backgroundAudioManager.onPlay(() => {
				this.player.paused = false;
			})

			// 背景音频暂停事件
			this.backgroundAudioManager.onPause(() => {
				this.player.paused = true;
			})

			// 背景音频进入可以播放状态，但不保证后面可以流畅播放
			this.backgroundAudioManager.onCanplay(() => {
				this.player.duration = this.backgroundAudioManager.duration;
			})

			this.backgroundAudioManager.onTimeUpdate(() => {
				this.player.currentTime = this.backgroundAudioManager.currentTime;
			})

			// 背景音频自然播放结束事件
			this.backgroundAudioManager.onEnded(() => {
				this.next();
			})

			this.backgroundAudioManager.onPrev(() => {
				this.last();
			})

			this.backgroundAudioManager.onNext(() => {
				this.next();
			})
		},
		play: function() {
			if (!this.player.music) {
				return;
			}
			if (this.backgroundAudioManager.paused) {
				this.backgroundAudioManager.play();
			}
		},
		seek: function(position) {
			if (!this.player.music) {
				return;
			}
			this.backgroundAudioManager.seek(position);
			this.backgroundAudioManager.play();
		},
		pause: function() {
			if (!this.player.music) {
				return;
			}
			if (!this.backgroundAudioManager.paused) {
				this.backgroundAudioManager.pause();
			}
		},
		next: function() {
			if (this.data.length === 0) {
				return;
			}
			let nextIndex = 0;
			if (this.player.music) {
				for (let i in this.data) {
					// 找到当前正在播放的音乐
					if (this.data[i].name === this.player.music.name) {
						nextIndex = parseInt(i) + 1;
						break;
					}
				}
				if (nextIndex >= this.data.length) {
					nextIndex = 0;
				}
			}
			console.log("nextIndex = ", nextIndex);
			this.setMusic(this.data[nextIndex]);
			this.play()
		},
		last: function() {
			if (this.data.length === 0) {
				return;
			}
			let lastIndex = this.data.length - 1;
			if (this.player.music) {
				for (let i in this.data) {
					if (this.data[i].name === this.player.music.name) {
						lastIndex = parseInt(i) - 1;
						break;
					}
				}
				if (lastIndex < 0) {
					lastIndex = this.data.length - 1;
				}
			}
			console.log("lastIndex = ", lastIndex);
			this.setMusic(this.data[lastIndex]);
			this.play()
		}
	},
});
